import React, { useMemo, useCallback, memo } from "react";

interface Product {
  id: number;
  name: string;
  price: number;
}

interface CartProps {
  products: Product[];
}

const CartItem: React.FC<Product> = memo(({ name, price }) => (
  <li>
    {name} - ¥{price}
  </li>
));

const Cart: React.FC<CartProps> = ({ products }) => {
  const totalPrice = useMemo(() => {
    console.log("计算总价...");
    return products.reduce((sum, product) => sum + product.price, 0);
  }, [products]);

  const handleCheckout = useCallback(() => {
    console.log("结账处理...");
    // 假设这里有复杂的结账逻辑
  }, []);

  return (
    <div>
      <h2>购物车</h2>
      <ul>
        {products.map((product) => (
          <CartItem key={product.id} {...product} />
        ))}
      </ul>
      <p>总价: ¥{totalPrice}</p>
      <button onClick={handleCheckout}>结账</button>
    </div>
  );
};

export default Cart;
